package com.yungam.influxdb.service;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.QueryApi;
import com.influxdb.client.WriteApi;
import com.influxdb.query.FluxTable;
import com.yungam.influxdb.config.DbConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ThreeViewService {

    @Resource
    private DbConfig config;

    @Getter
    private InfluxDBClient influxDBClient;
    @Getter
    private WriteApi writeApi;
    @Getter
    private QueryApi queryApi;

    @PostConstruct
    public void init() {
        influxDBClient = InfluxDBClientFactory.create(
                config.getInflux().getUrl(),
                config.getInflux().getToken().toCharArray(),
                config.getInflux().getOrg(),
                config.getInflux().getBucket());
        writeApi = influxDBClient.getWriteApi();
        queryApi = influxDBClient.getQueryApi();
    }

    /*
     * 根据 ipList 和 idList 查询实时数据
     * */
    public List<FluxTable> queryRealData(Map<String, List<Integer>> map, List<String> ipList) {
        StringBuilder sb = new StringBuilder();
        for (String ip : ipList) {
            if (!map.containsKey(ip)) continue;
            List<Integer> idList = map.get(ip);
            StringBuilder str = new StringBuilder();
            str.append(" or ( r.ip == \"").append(ip).append("\" and (");
            for (int i = 0, len = idList.size(); i < len; i++) {
                if (i == 0) {
                    str.append(" r.id == \"").append(idList.get(i)).append("\"");
                } else {
                    str.append(" or r.id == \"").append(idList.get(i)).append("\"");
                }
            }
            str.append(") )");
            sb.append(str);
        }
        String filter = sb.substring(" or ".length());
        String queryStr = "from(bucket:\"" + config.getInflux().getBucket() + "\")" +
                "|> range(start:-2m)" +
                "|> filter(fn: (r) => r[\"_measurement\"] == \"flink_data\")" +
                "|> filter(fn:(r)=>" + filter + ")" +
                "|> last()";
        try {
            return queryApi.query(queryStr);
        } catch (Exception e) {
            log.error("读取错误, 重新创建QueryApi", e);
            queryApi = influxDBClient.getQueryApi();
            return queryApi.query(queryStr);
        }
    }
}
